package Designattern.Day3.Proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/5/21 10:45
 * @description： 动态对象
 * 根据你输入的对象，返回一个动态对象
 */
public class ProxyTeacherDAO {
    private Object target;

    public ProxyTeacherDAO(Object target) {
        this.target = target;
    }

    //动态代理返回一个代理对象
    public Object getProxyTarget(){

        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("动态代理开始");
                Object invoke = method.invoke(target, args);
                System.out.println("动态代理结束");
                return invoke;
            }
        });
    }

    public static void main(String[] args) {

        //创建代理对象
        ITeacherDAO proxyTarget = (ITeacherDAO) new ProxyTeacherDAO(new TeacherDAO()).getProxyTarget();
        System.out.println(proxyTarget);
        proxyTarget.teach();
    }
}
